package com.loongtech.bi.action.biflow;

import com.loongtech.bi.action.Base2BiSearchAction;
import com.loongtech.bi.action.UIHelper;
import com.loongtech.bi.manager.flow.HadoopQueryManager;
import com.loongtech.bi.manager.system.BiPlatformManager;
import com.loongtech.bi.manager.system.GameParamConfigManager;
import com.loongtech.bi.support.CommonGameParam;
import com.loongtech.core.util.Time;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.util.*;
import java.util.Map.Entry;

/**
 * 
 * ClassName: RechargeFlowAction
 * 
 * @Description: 实时充值流水
 * @author liuchen
 * @date 2017-5-16 上午10:27:35
 */
@Controller
@Scope("prototype")
@RequestMapping("flow/rechargeFlow")
public class RechargeFlowNewAction extends Base2BiSearchAction {
	private static final long serialVersionUID = 1L;
	@Autowired
	HadoopQueryManager hadoopQueryManager;

	@RequestMapping(value = "updateServer.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void updateServer(HttpServletRequest request, HttpServletResponse response, String serverid, String callback) {
		try {
			queryServer = serverid;
			selectServerItems();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "0");
			result.put("channelItmes", channelItmes);
			result.put("platformItmes", platformItmes);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	@RequestMapping(value = "updateChannel.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void updateChannel(HttpServletRequest request, HttpServletResponse response, String channelid,
			String callback) {
		try {
			queryChannel = channelid;
			selectChannelItems();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "0");
			result.put("serverItmes", serverItmes);
			result.put("platformItmes", platformItmes);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	@RequestMapping(value = "updatePlatform.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void updatePlatform(HttpServletRequest request, HttpServletResponse response, String platformid,
			String callback) {
		try {
			queryPlatform = platformid;
			selectPlatformItems();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "0");
			result.put("serverItmes", serverItmes);
			result.put("channelItmes", channelItmes);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	@RequestMapping(value = "initParam.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void initParam(HttpServletRequest request, HttpServletResponse response, String callback) {
		try {
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "0");
			result.put("serverItmes", serverItmes);
			result.put("channelItmes", channelItmes);
			result.put("platformItmes", platformItmes);
			result.put("addtypeItmes", GameParamConfigManager.getItems(CommonGameParam.RECHARGE_TYPE));
			result.put("productItmes", GameParamConfigManager.getItems(CommonGameParam.PRODUCT_NAME));
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	@RequestMapping(value = "search.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void search(HttpServletRequest request, HttpServletResponse response, @RequestParam String params,
			String callback) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Map<String, Object> m = jsonToMap(params);
			Date dateStart = Time.formatDate((String) m.get("dateStart"), "yyyy-MM-dd");
			Date dateEnd = Time.formatDate((String) m.get("dateEnd"), "yyyy-MM-dd");
			String orderid = (String) m.get("orderid");
			String orderid2 = (String) m.get("orderid2");
			String userid = (String) m.get("userid");
			String roleid = (String) m.get("roleid");

			String platform = (String) m.get("platform");
			String channel = (String) m.get("channel");
			String serverid = (String) m.get("serverid");

			Integer flag = Integer.valueOf((String) m.get("flag"));
			Integer addtype = Integer.valueOf((String) m.get("addtype"));
			Integer productid = Integer.valueOf((String) m.get("productid"));
			// 开始结束时间不能大于当前时间60天
			if (Time.getInterval(new Date(), dateStart) > 60 || Time.getInterval(new Date(), dateEnd) > 60) {
				result.put("res", "1");
				result.put("msg", "开始结束时间不能小于当前时间60天!");
				printToJson(response, result, callback);
				return;
			}

			// 外部订单号，内部订单号，用户ID，角色ID必要有一个非空
			if (StringUtils.isBlank(orderid) && StringUtils.isBlank(orderid2) && StringUtils.isBlank(userid)
					&& StringUtils.isBlank(roleid)) {
				result.put("res", "1");
				result.put("msg", "外部订单号，内部订单号，用户ID，角色ID必须至少有一个非空!");
				printToJson(response, result, callback);
				return;
			}
			if (HadoopQueryManager.VISIT_QUEUE.offer("RechargeFlowNewAction")) {
				System.out.println("VISIT_QUEUE offer RechargeFlowNewAction ok!");

				StringBuffer sql = new StringBuffer();
				sql.append("select innerorderid,outerorderid,logtime,platform,channel,serverid,mac,userid,roleid,rolelevel,viplevel,totalcash,cashadd,yuanbaoadd,flag,addtype,'-' from addcash where 1=1 ");
				if (userid != null && !"".equals(userid)) {
					sql.append(" and userid = '");
					sql.append(userid.trim());
					sql.append("' ");
				}
				if (!StringUtils.isBlank(roleid)) {
					sql.append(" and cast(roleid as string) = '");
					sql.append(roleid);
					sql.append("' ");
				}
				if (!"0".equals(platform)) {
					sql.append(" and platform = ");
					sql.append(platform);
				}
				if (!"0".equals(channel)) {
					sql.append(" and channel = '");
					sql.append(channel);
					sql.append("' ");
				}
				if (!"0".equals(serverid)) {
					sql.append(" and serverid = ");
					sql.append(serverid);
				}
				if (orderid != null && !"".equals(orderid)) {
					sql.append(" and outerorderid = '");
					sql.append(orderid.trim());
					sql.append("' ");
				}
				if (orderid2 != null && !"".equals(orderid2)) {
					sql.append(" and innerorderid = '");
					sql.append(orderid2.trim());
					sql.append("' ");
				}
				if (flag != -1) {
					sql.append(" and flag = ");
					sql.append(flag);
				}
				if (addtype != -99999) {
					sql.append(" and bitand(addtype,");
					sql.append(addtype);
					sql.append(")=");
					sql.append(addtype);
				}
				if (productid != -99999) {
					sql.append(" and productid = ");
					sql.append(productid);
				}
				sql.append(" and dt >= '");
				sql.append(Time.getDateStr(dateStart));
				sql.append("' and dt <= '");
				sql.append(Time.getDateStr(dateEnd));
				sql.append("' ");
				sql.append(" order by logtime desc ");

				System.out.println(sql.toString());
				Entry<List<String>, List<Object[]>> ret = hadoopQueryManager.executeSQL(sql.toString());
				if (null == ret || null == ret.getKey() || ret.getKey().isEmpty() || null == ret.getValue()) {
                    result.put("res", new ArrayList<Object[]>());
                    result.put("data", "");
                    printToJson(response, result, callback);
					return;
				}
				List<Object[]> lo = ret.getValue();

				for (Object[] o : lo) {
					o[3] = BiPlatformManager.getPlatformNameById((String) o[3]);
					o[4] = BiPlatformManager.getChannelNameById((String) o[4]);
					o[5] = BiPlatformManager.getServerNameById((String) o[5]);
					o[11] = getMoeny(o[11]);
					o[12] = getMoeny(o[12]);
					o[14] = "1".equals((String) o[14]) ? "是" : "否";
					o[15] = getAddType(o[15]) + "(" + o[15] + ")";
					// o[16] = getProductName(o[16]);
				}
				result.put("res", "0");
				result.put("data", lo);
				printToJson(response, result, callback);
			} else {
				System.out.println("VISIT_QUEUE offer RechargeFlowNewAction failed!");
				result.put("res", "1");
				result.put("msg", "当前系统正被访问，为保证服务器稳定，请稍后再试!");
				printToJson(response, result, callback);
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
		}
	}

	protected DecimalFormat df = new DecimalFormat("######0.00");

	private Map<String, String> addtypeItmesRevise = GameParamConfigManager
			.getItemsRevise(CommonGameParam.RECHARGE_TYPE); // 支付方式下拉反转

	private Map<String, String> productItmesRevise = GameParamConfigManager
			.getItemsRevise(CommonGameParam.PRODUCT_NAME); // 商品名称下拉反转

	// 查询充值类型
	public String getAddType(Object addType) {
		String key = addType == null ? "" : Math.abs(Integer.parseInt(addType.toString())) + "";
		return (addtypeItmesRevise.get(key) == null) ? key : addtypeItmesRevise.get(key);
	}

	public String getProductName(Object product) {
		String key = product == null ? "" : Math.abs(Integer.parseInt(product.toString())) + "";
		return (productItmesRevise.get(key) == null) ? key : productItmesRevise.get(key);
	}

	public String getMoeny(Object addType) {
		return null != addType ? df.format(UIHelper.getYuan(Double.valueOf(addType.toString()))) : "";
	}

	@Override
	public void search() {
		// TODO Auto-generated method stub

	}

	@Override
	protected String csvContent() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected String csvFileName() {
		// TODO Auto-generated method stub
		return null;
	}
}
